% Log likelihood to obtain bidder parameters,
% draws on the Poisson structure with mean lambda
% Called from "main"
% ---------------------------------------------- %
function[LL] = bidderLLlambda(thetab,parameters,data,PAR)
  lambda = parameters(1);
  
  if PAR.generalized == 0 %Gaussian, or other two-parameter distribution    
        db  = makedist(PAR.dist,thetab(1),thetab(2));
        CDF = @(x) cdf(db,x);
        PDF = @(x) pdf(db,x);
  else %Generalized gaussian
        CDF = @(x) ggd_cdf(x,thetab);
        PDF = @(x) ggd_pdf(x,thetab);
        
        %Exclude data outside support (LL not defined)
        if thetab(3)>0
            ub = thetab(1)+thetab(2)/thetab(3);
            data = data(log(data.reserve_bot)-data.Quality<ub,:);
        else
            lb = thetab(1)+thetab(2)/thetab(3);
            data = data(log(data.reserve_bot)-data.Quality>lb,:);
        end
  end
  if PAR.add0topois == 0 % Most basic specification: Poisson
      sharenobidders = 0;
  else % Allow for structural share of no bidders in posr auctions
      sharenobidders = parameters(2);
  end
  pdfs_nbidders = (1-sharenobidders).*pdf('pois',0:PAR.maxn,lambda); 
  pdfs_nbidders(1) = sharenobidders+pdfs_nbidders(1);
   
    % number bidders
    aa = data.numberbidders;
    
    % log residual reserve price per bottle
    rtilde = log(data.reserve_bot)-data.Quality;
 
    % Select auctions with 0,1,>1 actual bidders
    T  = length(rtilde);
    t  = 1:1:T;
    indexa0 = t(aa==0);
    indexa1 = t(aa==1);
    indexa2 = t(aa>=2);
    
    % Functions for two parts of the likelihood
    binomaoutofn   = @(r,a,n) binopdf(n-a,n,CDF(r));
    probsh         = @(H,n)   n.*(n-1).*((CDF(H).^(n-2)).*(1-CDF(H)).*PDF(H)) ;
    
    % prob actual bidders given potential bidders (=0 for a>n, and 1 only for n=0 if a=0)
    LLmat = ones(T,PAR.maxn+1);
    for n = 0:PAR.maxn
       LLmat(indexa0,n+1)  = binomaoutofn(rtilde(indexa0), aa(indexa0), n);
       LLmat(indexa1,n+1)  = binomaoutofn(rtilde(indexa1), aa(indexa1), n);
    end
    
    % prob sh value given actual bidders (probsh=NaN for a =0,1 but these are
    % excluded, so given that SHvec has ones(T,1) these a=0,1 observations will correctly be
    % set equal to 1)
    SHmat = ones(T,PAR.maxn+1);
    for n = 0:PAR.maxn
        SHmat(indexa2,n+1) = probsh(data.Uhat(indexa2),n);
    end
    
    % prob potential bidders given parameter(s)
    Pmat      = repmat(pdfs_nbidders,T,1);
     
    % Combine Likelihood (a=0,a=1), with Likelihood(a=2), and probabilities
    % a=0,1,observed a>1
    jointprobobs = sum(LLmat.*SHmat.*Pmat,2);
    LL = - sum(log(jointprobobs)); 
end
